package com.yuntsg.nnsfcp.service.back;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.config.AliWuLiuConfig;
import com.yuntsg.nnsfcp.config.UploadConfig;
import com.yuntsg.nnsfcp.entity.SearchEntity;
import com.yuntsg.nnsfcp.front.entity.CnkiDetail;
import com.yuntsg.nnsfcp.front.entity.OrderBaseInfo;
import com.yuntsg.nnsfcp.front.mapper.*;
import com.yuntsg.nnsfcp.service.front.OrderService;
import com.yuntsg.nnsfcp.service.front.pojo.CnkiListEntity;
import com.yuntsg.nnsfcp.service.front.ut.DateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 2020年2月20日11:38:37
 * 处理知网数据模板
 * */

@Service
public class CnkiService {
    @Resource
    CnkiDetailMapper cnkiDetailMapper;
    @Resource
    HttpServletResponse response;
    @Resource
    OrderIndexTimeMapper orderIndexTimeMapper;
    @Resource
    EmployeeMapper employeeMapper;
    @Resource
    WosdetailMapper wosdetailMapper;
    @Resource
    CheckProgressMapper checkProgressMapper;
    @Resource
    HttpServletRequest request;
    @Resource
    TemplateMapper templateMapper;
    @Resource
    OrderBaseInfoMapper orderBaseInfoMapper;
    @Resource
    private UploadConfig uploadConfig;
    @Resource
    private AliWuLiuConfig wuLiuConfig;
    @Resource
    private OrderService orderService;

    public String CSSCIShouLuPath(OrderBaseInfo orderBaseInfo) throws Exception {
        //序号	文献信息	作者顺序	收录库	文献级别
        // 1 程国赋.“唐人始有意为小说”刍议[J].中国文化研究,2017(04):38-50.	第一作者	CSSCI核心库
        String fileName = System.currentTimeMillis() + ".docx";
        String fileNamePdf = fileName.replace(".docx", "") + ".pdf";
        String paperList = orderBaseInfo.getPaperList();
        List<SearchEntity> cnkiDetails = JSON.parseArray(paperList, SearchEntity.class);
//        List<CnkiDetail> cnkiDetails = cnkiDetailMapper.selectList(new QueryWrapper<CnkiDetail>().eq("apply_id", orderBaseInfo.getApplyId()));
        String fromPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + "/" + "收录模板(CSSCI).docx");
        Document doc = new Document(fromPath);


        Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
//        String breakLine = ControlChar.LINE_BREAK;
        int s = 1;
        for (SearchEntity cnkiDetail : cnkiDetails) {
            Node deepClone = table.getLastRow().deepClone(true);
            Range range = table.getLastRow().getRange();
            StringBuffer stringBuffer = new StringBuffer();
//            CnkiListEntity cnkiListEntity = JSONObject.parseObject(cnkiDetail.getDetailList(), CnkiListEntity.class);
            stringBuffer.append(cnkiDetail.getAuthor() == null ? "" : cnkiDetail.getAuthor() + ".");
            stringBuffer.append(cnkiDetail.getTitle() == null ? "" : cnkiDetail.getTitle() + "[J].");
            stringBuffer.append(cnkiDetail.getSource() == null ? "" : cnkiDetail.getSource() + ",");
            stringBuffer.append(cnkiDetail.getPages() == null ? "" : cnkiDetail.getPages());
            HashMap<String, String> map = new HashMap<>(16);
            String db = "CSSCI";
//            map.put("SCIE", "0");
//            map.put("CSCD", "1");
//            map.put("SSCI", "2");
//            map.put("A&HCI", "3");
//            map.put("CPCI-S", "4");
//            map.put("CPCI-SSH", "5");
//            map.put("CSSCI", "6");
//            map.put("CNKI", "7");
//            map.put("EI", "8");
//            for (Map.Entry<String, String> a : map.entrySet()) {
//                if (a.getValue().equals("7")) {
//                    db = a.getKey();
//                }
//            }
            // 1 程国赋.“唐人始有意为小说”刍议[J].中国文化研究,2017(04):38-50.	第一作者	CSSCI核心库
            String info = stringBuffer.toString();
            String au = cnkiDetail.getAuthor();
            String level = "--";
            //xh	info	au	db	level

            table.getRows().add(deepClone);
            s++;
        }
        table.getLastRow().remove();
        String ToPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/");
        try {
            File targetFile = new File(ToPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        doc.save(ToPath + fileName, SaveFormat.DOCX);
        doc.save(ToPath + fileNamePdf, SaveFormat.PDF);
        orderBaseInfo.setResultReportWord(uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName);
        orderBaseInfoMapper.updateById(orderBaseInfo);
        System.out.println("知网收录模板路径" + uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName);
        return uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName;
    }


    public String cnkiShouLuPath(OrderBaseInfo orderBaseInfo) throws Exception {
        //序号	文献信息	作者顺序	收录库	文献级别
        // 1 程国赋.“唐人始有意为小说”刍议[J].中国文化研究,2017(04):38-50.	第一作者	CSSCI核心库
        String fileName = System.currentTimeMillis() + ".docx";
        String fileNamePdf = fileName.replace(".docx", "") + ".pdf";
        List<CnkiDetail> cnkiDetails = cnkiDetailMapper.selectList(new QueryWrapper<CnkiDetail>().eq("apply_id", orderBaseInfo.getApplyId()));
        String fromPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + "/" + "收录模板(CNKI  CSSCI).docx");
        Document doc = new Document(fromPath);


        Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        String breakLine = ControlChar.LINE_BREAK;
        int s = 1;
        for (CnkiDetail cnkiDetail : cnkiDetails) {
            Node deepClone = table.getLastRow().deepClone(true);
            Range range = table.getLastRow().getRange();
            StringBuffer stringBuffer = new StringBuffer();
            CnkiListEntity cnkiListEntity = JSONObject.parseObject(cnkiDetail.getDetailList(), CnkiListEntity.class);
            stringBuffer.append(cnkiListEntity.getAuthor() == null ? "" : cnkiListEntity.getAuthor() + ".");
            stringBuffer.append(cnkiListEntity.getTitle() == null ? "" : cnkiListEntity.getTitle() + "[J].");
            stringBuffer.append(cnkiListEntity.getSourceCn() == null ? "" : cnkiListEntity.getSourceCn() + ",");
            stringBuffer.append(cnkiListEntity.getNianQi() == null ? "" : cnkiListEntity.getNianQi() + ":");
            stringBuffer.append(cnkiListEntity.getPage() == null ? "" : cnkiListEntity.getPage());
            HashMap<String, String> map = new HashMap<>(16);
            String db = "";
            map.put("SCIE", "0");
            map.put("CSCD", "1");
            map.put("SSCI", "2");
            map.put("A&HCI", "3");
            map.put("CPCI-S", "4");
            map.put("CPCI-SSH", "5");
            map.put("CSSCI", "6");
            map.put("CNKI", "7");
            map.put("EI", "8");
            for (Map.Entry<String, String> a : map.entrySet()) {
                if (a.getValue().equals("7")) {
                    db = a.getKey();
                }
            }
            // 1 程国赋.“唐人始有意为小说”刍议[J].中国文化研究,2017(04):38-50.	第一作者	CSSCI核心库
            String info = stringBuffer.toString();
            String au = cnkiDetail.getAuthorOrder();
            String level = cnkiDetail.getPeriodicalClass() == null ? "--" : cnkiDetail.getPeriodicalClass();
            //xh	info	au	db	level

            table.getRows().add(deepClone);
            s++;
        }
        table.getLastRow().remove();
        String ToPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/");
        try {
            File targetFile = new File(ToPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        doc.save(ToPath + fileName, SaveFormat.DOCX);
        doc.save(ToPath + fileNamePdf, SaveFormat.PDF);
        orderBaseInfo.setResultReportWord(uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName);
        orderBaseInfoMapper.updateById(orderBaseInfo);
        System.out.println("知网收录模板路径" + uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName);
        return uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName;
    }


    public String cnkiShouLuYinYongPath(OrderBaseInfo orderBaseInfo) throws Exception {
        //序号	文献信息	作者顺序	CSSCI他引次数	CNKI他引次数	收录库	文献级别
        //1	程国赋.“唐人始有意为小说”刍议[J].中国文化研究,2017(04):38-50.	第一作者			CSSCI
        String fileName = System.currentTimeMillis() + ".docx";
        String fileNamePdf = fileName.replace(".docx", "") + ".pdf";
        List<CnkiDetail> cnkiDetails = cnkiDetailMapper.selectList(new QueryWrapper<CnkiDetail>().eq("apply_id", orderBaseInfo.getApplyId()));
        String fromPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + "/" + "收录引用模板(CNKI  CSSCI).docx");
        Document doc = new Document(fromPath);


        //计算全部他引次数
        int allTayin = 0;
        for (int i = 0; i < cnkiDetails.size(); i++) {
            allTayin += Integer.parseInt(cnkiDetails.get(i).getCitedNum());
        }

        Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        String breakLine = ControlChar.LINE_BREAK;
        int s = 1;
        for (CnkiDetail cnkiDetail : cnkiDetails) {
            Node deepClone = table.getLastRow().deepClone(true);
            Range range = table.getLastRow().getRange();
            StringBuffer stringBuffer = new StringBuffer();
            CnkiListEntity cnkiListEntity = JSONObject.parseObject(cnkiDetail.getDetailList(), CnkiListEntity.class);
            stringBuffer.append(cnkiListEntity.getAuthor() == null ? "" : cnkiListEntity.getAuthor() + ".");
            stringBuffer.append(cnkiListEntity.getTitle() == null ? "" : cnkiListEntity.getTitle() + "[J].");
            stringBuffer.append(cnkiListEntity.getSourceCn() == null ? "" : cnkiListEntity.getSourceCn() + ",");
            stringBuffer.append(cnkiListEntity.getNianQi() == null ? "" : cnkiListEntity.getNianQi() + ":");
            stringBuffer.append(cnkiListEntity.getPage() == null ? "" : cnkiListEntity.getPage());
            HashMap<String, String> map = new HashMap<>(16);
            String db = "";
            map.put("SCIE", "0");
            map.put("CSCD", "1");
            map.put("SSCI", "2");
            map.put("A&HCI", "3");
            map.put("CPCI-S", "4");
            map.put("CPCI-SSH", "5");
            map.put("CSSCI", "6");
            map.put("CNKI", "7");
            map.put("EI", "8");
            for (Map.Entry<String, String> a : map.entrySet()) {
                if (a.getValue().equals("7")) {
                    db = a.getKey();
                }
            }
            //1	程国赋.“唐人始有意为小说”刍议[J].中国文化研究,2017(04):38-50.	第一作者			CSSCI
            String info = stringBuffer.toString();
            String au = cnkiDetail.getAuthorOrder();
            String ty = cnkiDetail.getCitedNum();
            String level = cnkiDetail.getPeriodicalClass() == null ? "--" : cnkiDetail.getPeriodicalClass();
            //xh	info	au	db	level

            table.getRows().add(deepClone);
            s++;
        }
        table.getLastRow().remove();
        String ToPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/");
        try {
            File targetFile = new File(ToPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        doc.save(ToPath + fileName, SaveFormat.DOCX);
        doc.save(ToPath + fileNamePdf, SaveFormat.PDF);
        orderBaseInfo.setResultReportWord(uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName);
        orderBaseInfoMapper.updateById(orderBaseInfo);
        System.out.println("知网收录引用模板路径" + uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName);
        return uploadConfig.getUploadPath() + DateUtil.getCurrentYmdStr() + "/" + fileName;
    }


}
